package pingpongdojo.model;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class GameManager {

	public static interface GameListener {
		public void onSetCurrentGame(Game game);

		public void onGameUpdate(Game game);
	}

	private Game currentGame;

	private List<Game> activeGames = new ArrayList<Game>();
	private List<Game> completedGames = new ArrayList<Game>();

	private List<GameListener> gameListeners = new ArrayList<GameListener>();

	public List<Game> getActiveGames() {
		return getActiveGames(ModelFactory.getInstance().getUserManager()
				.getCurrentUser());
	}

	public List<Game> getActiveGames(User user) {
		List<Game> games = new ArrayList<Game>();
		for (Game game : activeGames) {
			if (game.getCurrentPlayer().equals(user)) {
				games.add(game);
			}
		}

		return games;
	}

	public Game createGame(String name, User codePlayer, User testPlayer) {
		Game game = new Game(name, codePlayer, testPlayer);
		activeGames.add(game);
		return game;
	}

	public void orderGamesByDateDescending() {
		Collections.sort(activeGames, new Comparator<Game>() {
			public int compare(Game game1, Game game2) {
				return game2.getDateLastPlayed().compareTo(
						game1.getDateLastPlayed());
			}
		});
	}

	public void addGameListener(GameListener listener) {
		gameListeners.add(listener);
	}

	public void removeGameListener(GameListener listener) {
		gameListeners.remove(listener);
	}

	public Game getCurrentGame() {
		return currentGame;
	}

	public void setCurrentGame(Game game) {
		System.out.println("Current game set to: " + game);

		this.currentGame = game;

		for (GameListener gameListener : getGameListeners()) {
			gameListener.onSetCurrentGame(game);
		}
	}

	public void fireGameUpdateEvent() {
		fireGameUpdateEvent(getCurrentGame());
	}

	public void fireGameUpdateEvent(Game game) {
		for (GameListener gameListener : getGameListeners()) {
			gameListener.onGameUpdate(game);
		}
	}

	protected List<GameListener> getGameListeners() {
		return new ArrayList<GameListener>(gameListeners);
	}

	public void endGame(Game game) {
		game.end();
		activeGames.remove(game);
		completedGames.add(game);
		setCurrentGame(null);
	}
}
